package com.longcai.controller.goods;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.WriterException;
import com.longcai.bean.PageHelper;
import com.longcai.entity.homegood.ClyjGoodsHomepage;
import com.longcai.entity.homegood.ClyjGoodsPics;
import com.longcai.entity.homegood.ClyjGoodsSpec;
import com.longcai.entity.homegood.ClyjGoodsVo;
import com.longcai.entity.homepage.ClyjSeckillGoods;
import com.longcai.entity.homepage.GoodsClass;
import com.longcai.entity.sys.SysRoleUser;
import com.longcai.entity.sys.SysUser;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.SysRoleUserService;
import com.longcai.service.SysUserService;
import com.longcai.service.goods.ClyjGoodsHomepageService;
import com.longcai.service.goods.ClyjGoodsPicsService;
import com.longcai.service.goods.ClyjSeckillGoodsService;
import com.longcai.util.LoginUser;
import com.longcai.util.OSSUtils;
import com.longcai.util.QRCodeUtils;
import com.longcai.util.UserUtil;

import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 首页商品表 前端控制器
 * </p>
 *
 * @author LWK
 * @since 2019-03-22
 */
@Controller
@RequestMapping("/clyjGoods")
public class ClyjGoodsHomepageController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ClyjGoodsHomepageService clyjGoodsHomepageService;
    @Autowired
    private ClyjGoodsPicsService picsService;
    @Autowired
    private SysRoleUserService sysRoleUserService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ClyjSeckillGoodsService skillService;
    
    /**
     * 查询角色为供应商的用户
     *
     * @return
     */
    @GetMapping(value="getSupplier")
    @ResponseBody
    public List<SysUser> getSupplier() {
    	QueryWrapper<SysRoleUser> w = new QueryWrapper<SysRoleUser>();
    	List<SysUser> sysUser = new ArrayList<SysUser>();
    	w.eq("roleId", 3);
    	List<SysRoleUser> selectList = sysRoleUserService.selectList(w);
    	if(selectList==null || selectList.size()==0) {
            return null;
        }
    	for (SysRoleUser sysRoleUser : selectList) {
			//根据用户id获取用户信息
    		SysUser user = sysUserService.selectById(sysRoleUser.getUserId());
    		sysUser.add(user);
		}
         return sysUser;
    }

    /**
     * 分页查询品牌
     *
     * @return
     */
    @GetMapping(value = "getGoods")
    @ResponseBody
    public PageTableResponse getGoods(ClyjGoodsHomepage sysRole, PageHelper pageHelper) {
    	Page<ClyjGoodsHomepage> page =new Page<ClyjGoodsHomepage>(pageHelper.getStart(),pageHelper.getLength());
    	QueryWrapper<ClyjGoodsHomepage> w = new QueryWrapper<ClyjGoodsHomepage>();
    	if(sysRole.getGoodsName()!=null && sysRole.getGoodsName()!="")
    		w.like("goods_name", sysRole.getGoodsName());
    	//获取当前用户信息
    	LoginUser loginUser = UserUtil.getLoginUser();
    	if(loginUser.getId()!=1)
    		//w.eq("supplier_id", loginUser.getId());
    	w.orderByDesc("month_sales");
        IPage<ClyjGoodsHomepage> sysRoleIPage = clyjGoodsHomepageService.selectPage(page, w);
        PageTableResponse pageTableResponse = new PageTableResponse(sysRoleIPage.getTotal(),
                sysRoleIPage.getTotal(), sysRoleIPage.getRecords());
        return pageTableResponse;
    }

    /**
     * 新增商品
     *
     * @param goodsClas2s
     * @param goodsPic2
     * @param goodsBanner2
     * @return
     */
    @PostMapping(value = "saveGoods")
    @ResponseBody
    public boolean save(ClyjGoodsVo goodsClas2s, MultipartFile goodsPic2, MultipartFile goodsBanner2) throws IOException, WriterException {
        if (goodsPic2 != null) {
            //文档上传oss
            try {
                String fileName = goodsPic2.getOriginalFilename();
                String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
                InputStream inputStream = goodsPic2.getInputStream();
                Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODS/PIC/");
                goodsClas2s.setGoodsPic(uploadByInputStream.get("path").toString());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (goodsBanner2 != null) {
            //文档上传oss
            try {
                String fileName = goodsBanner2.getOriginalFilename();
                String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
                InputStream inputStream = goodsBanner2.getInputStream();
                Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODS/BANNER/");
                goodsClas2s.setGoodsBanner(uploadByInputStream.get("path").toString());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (goodsClas2s.getGoodsId() == null || goodsClas2s.getGoodsId() == "" || goodsClas2s.getGoodsId().equals("")) {
            //新增
            goodsClas2s.setGoodsId(UUID.randomUUID().toString());
            goodsClas2s.setCreateTime(new Date());
            //生成二维码
            //存放路径
            /*String realPath = this.getClass().getClassLoader().getResource("static/qrcode").getPath();
            String substring = realPath.substring(0,1);
            if(substring.equals("/"))
            	realPath = realPath.substring(1);
            //跳转地址
            String content = "https://www.baidu.com";
            //名称
            String name = "image.jpg";
            File file = QRCodeUtils.testEncode(realPath, content, name);
            if (file != null) {
                //文档上传oss
                try {
                    String pox = name.substring(name.lastIndexOf(".") + 1);
                    InputStream inputStream = new FileInputStream(file);
                    Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, name, "CLYJ/GOODSCODE/");
                    goodsClas2s.setCode(uploadByInputStream.get("path").toString());
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }*/
            goodsClas2s.setGoodsStatus(0);
            this.clyjGoodsHomepageService.insert(goodsClas2s);


        } else {
            goodsClas2s.setUpdateTime(new Date());
            this.clyjGoodsHomepageService.updateById(goodsClas2s);
        }
        //删除分类信息
        clyjGoodsHomepageService.deleteType(goodsClas2s);
        //新增分类信息
        clyjGoodsHomepageService.insertType(goodsClas2s);
        //删除规格信息
        clyjGoodsHomepageService.deleteSpec(goodsClas2s);
        //新增规格信息
        clyjGoodsHomepageService.insertSpec(goodsClas2s);
        //删除商品图片表
        clyjGoodsHomepageService.deletePics(goodsClas2s);
        return true;
    }


    /**
     * 根据id获取商品
     *
     * @param goodsId
     * @return
     */
    @GetMapping("{goodsId}")
    @ApiOperation(value = "根据id获取商品")
    @ResponseBody
    public Map<String, Object> get(@PathVariable String goodsId) {
        Map<String, Object> map = new HashMap<String, Object>();
        ClyjGoodsHomepage selectById = clyjGoodsHomepageService.selectById(goodsId);
        map.put("data", selectById);
        //查询规格
        List<ClyjGoodsSpec> list = clyjGoodsHomepageService.getSpecByGoodsId(goodsId);
        if (list == null || list.size() == 0) {
            return map;
        }
        List<String> detailList = new ArrayList<String>();
        List<String> numList = new ArrayList<String>();
        List<BigDecimal> specPriceOldList = new ArrayList<BigDecimal>();
        List<BigDecimal> specPriceNewList = new ArrayList<BigDecimal>();
        List<BigDecimal> specYjList = new ArrayList<BigDecimal>();
        List<String> specKujgList = new ArrayList<String>();
        List<String> sortList = new ArrayList<String>();
        List<String> idList = new ArrayList<String>();
        List<List<String>> specPic = new ArrayList<List<String>>();
        for (ClyjGoodsSpec clyjGoodsSpec : list) {
            detailList.add(clyjGoodsSpec.getSpecDetail());
            numList.add(String.valueOf(clyjGoodsSpec.getSpecNum()));
            sortList.add(clyjGoodsSpec.getSpecSort());
            idList.add(clyjGoodsSpec.getSpecId());
            specPriceOldList.add(clyjGoodsSpec.getSpecPriceOld());
            specPriceNewList.add(clyjGoodsSpec.getSpecPriceNew());
            specYjList.add(clyjGoodsSpec.getSpecYj());
            specKujgList.add(clyjGoodsSpec.getSpecKcjg());
            //根据specid查询轮播图并将轮播图存入数组
            QueryWrapper<ClyjGoodsPics> wrapper = new QueryWrapper<ClyjGoodsPics>();
            wrapper.eq("spec_id", clyjGoodsSpec.getSpecId());
            wrapper.eq("pic_type", "1");
            List<ClyjGoodsPics> selectList = picsService.selectList(wrapper);
            if(selectList==null || selectList.size()==0)
            	continue;
            List<String> aList = new ArrayList<String>();
            for (ClyjGoodsPics clyjGoodsPics : selectList) {
                aList.add(clyjGoodsPics.getPicUrl());
            }
            specPic.add(aList);
        }
        ClyjGoodsVo s = new ClyjGoodsVo();
        s.setSpecDetail(detailList);
        s.setSpecPriceOld(specPriceOldList);
        s.setSpecPriceNew(specPriceNewList);
        s.setSpecYj(specYjList);
        s.setSpecKcjg(specKujgList);
        s.setSpecNum(numList);
        s.setSpecSort(sortList);
        s.setSpecId(idList);
        s.setSpecPic(specPic);
        map.put("data2", s);
        return map;
    }

    @GetMapping(value = "goodsId")
    @ResponseBody
    @ApiOperation(value = "根据brandid获取分类")
    public List<GoodsClass> listByBrandId(String goodsId) {
        return this.clyjGoodsHomepageService.listByBrandId(goodsId);
    }


    @RequestMapping(value = "saveSpecPic")
    @ResponseBody
    public boolean saveSpecPic(ClyjGoodsVo goodsClas2s, MultipartFile[] file0, MultipartFile[] file1, MultipartFile[] file2, MultipartFile[] file3, MultipartFile[] file4) throws Exception {
        boolean flag = true;
        List<String> specId = goodsClas2s.getSpecId();
        if (file0 == null || file0.length == 0) {
            return flag;
        }
        QueryWrapper<ClyjGoodsPics> wrapper = new QueryWrapper<ClyjGoodsPics>();
        wrapper.in("spec_id", specId);
        picsService.delete(wrapper);
        for (MultipartFile multipartFile : file0) {
            //上传文件
            String fileName = multipartFile.getOriginalFilename();
            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream inputStream = multipartFile.getInputStream();
            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODS/SPEC/");
            //数据库插入数据
            ClyjGoodsPics a = new ClyjGoodsPics();
            a.setGoodsId(goodsClas2s.getGoodsId());
            a.setPicUrl(uploadByInputStream.get("path").toString());
            a.setSpecId(specId.get(0));
            a.setId(UUID.randomUUID().toString());
            a.setPicType("1");
            a.setPicStatus("1");
            picsService.insert(a);
        }
        if (file1 == null || file1.length == 0) {
            return flag;
        }
        for (MultipartFile multipartFile : file1) {
            //上传文件
            String fileName = multipartFile.getOriginalFilename();
            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream inputStream = multipartFile.getInputStream();
            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODS/SPEC/");
            //数据库插入数据
            ClyjGoodsPics a = new ClyjGoodsPics();
            a.setGoodsId(goodsClas2s.getGoodsId());
            a.setPicUrl(uploadByInputStream.get("path").toString());
            a.setSpecId(specId.get(1));
            a.setId(UUID.randomUUID().toString());
            a.setPicType("1");
            a.setPicStatus("1");
            picsService.insert(a);
        }
        if (file2 == null || file2.length == 0) {
            return flag;
        }
        for (MultipartFile multipartFile : file2) {
            //上传文件
            String fileName = multipartFile.getOriginalFilename();
            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream inputStream = multipartFile.getInputStream();
            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODS/SPEC/");
            //数据库插入数据
            ClyjGoodsPics a = new ClyjGoodsPics();
            a.setGoodsId(goodsClas2s.getGoodsId());
            a.setPicUrl(uploadByInputStream.get("path").toString());
            a.setSpecId(specId.get(2));
            a.setId(UUID.randomUUID().toString());
            a.setPicType("1");
            a.setPicStatus("1");
            picsService.insert(a);
        }
        if (file3 == null || file3.length == 0) {
            return flag;
        }
        for (MultipartFile multipartFile : file3) {
            //上传文件
            String fileName = multipartFile.getOriginalFilename();
            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream inputStream = multipartFile.getInputStream();
            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODS/SPEC/");
            //数据库插入数据
            ClyjGoodsPics a = new ClyjGoodsPics();
            a.setGoodsId(goodsClas2s.getGoodsId());
            a.setPicUrl(uploadByInputStream.get("path").toString());
            a.setSpecId(specId.get(3));
            a.setId(UUID.randomUUID().toString());
            a.setPicType("1");
            a.setPicStatus("1");
            picsService.insert(a);
        }
        if (file4 == null || file0.length == 4) {
            return flag;
        }
        for (MultipartFile multipartFile : file4) {
            //上传文件
            String fileName = multipartFile.getOriginalFilename();
            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream inputStream = multipartFile.getInputStream();
            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODS/SPEC/");
            //数据库插入数据
            ClyjGoodsPics a = new ClyjGoodsPics();
            a.setGoodsId(goodsClas2s.getGoodsId());
            a.setPicUrl(uploadByInputStream.get("path").toString());
            a.setSpecId(specId.get(4));
            a.setId(UUID.randomUUID().toString());
            a.setPicType("1");
            a.setPicStatus("1");
            picsService.insert(a);
        }
        return flag;
    }
    
    @DeleteMapping("{goodsId}")
    @ApiOperation(value = "删除商品")
    @ResponseBody
    @PreAuthorize("hasAuthority('goods:good:del')")
    public void delete(@PathVariable String goodsId) {
        this.clyjGoodsHomepageService.deleteById(goodsId);
        //删除商品分类中间表的数据
        ClyjGoodsVo goodsClas2s = new ClyjGoodsVo();
        goodsClas2s.setGoodsId(goodsId);
        clyjGoodsHomepageService.deleteType(goodsClas2s);
        //删除商品规格中间表的数据
        clyjGoodsHomepageService.deleteSpec(goodsClas2s);
        //删除商品图片中间表的数据
        clyjGoodsHomepageService.deletePics(goodsClas2s);
        //删除商品秒杀数据
        QueryWrapper<ClyjSeckillGoods> wrapper = new QueryWrapper<ClyjSeckillGoods>();
        wrapper.eq("goods_id", goodsId);
        skillService.delete(wrapper);
    }
}

